const dateUtils = require('../../utils/defautils')
const utils = require("../../utils/index.js")
const {
SendverificationCode,
register,
option,
    smscode,
follow
} = require('../../api/login.js')
const {
    levelOption,
    sheng,
} = require('../../api/index.js')
const request = require('../../api/request')
Page({
data: {
levelTow:"yuanquList",
levelThree:"jiedaoList",
     xuehao:'',
     mima:'',
     xueshengxingming:'',
xingbieList: ["请选择性别", "男", "女"],
xingbieIndex: 0,
     xueyuan:'',
     zhuanye:'',
     nianji:'',
xueliList: ["请选择学历", "小学", "初中", "高中", "中专", "大专", "本科", "研究生", "博士"],
xueliIndex: 0,
shifoubiyeList: ["请选择是否毕业", "是", "否"],
shifoubiyeIndex: 0,
     biyenianfen:'',
xiangmufuzerenList: ["请选择项目负责人", "是", "否"],
xiangmufuzerenIndex: 0,
     suozaixuexiao:'',
     youxiang:'',
    touxiang:'',
    tempPathtouxiang:'../../static/upload.png',
     chuangyelingyu:'',
     canjiahuodong:'',
     canyuxiangmu:'',
leixingList:"在校生,毕业生".split(','),
leixingIndex:0,
     chengshi:'',
     yuanqu:'',
     jiedao:'',
     email:'',
         buttonText: '发送验证码',
         countdown: 60,
         canSendCode: true,
         smscode: "",
         inputSmscode: "",
    registerContainerClass: "",
    xuexiaoList: [],
    xuexiaoIndex: 0,
    xueyuanList: [],
    xueyuanIndex: 0,
    shoujihaoma: '',
    inputSmscode2: '',
    canSendSmsCode: true,
    buttonText2: '发送验证码',
    countdown2: 60,
    xueshengxingmingError: '',
    mimaError: '',
    mima2Error: '',
},

async onLoad(options) {
  if (options && options.phone) {
    this.setData({ shoujihaoma: options.phone });
  }
},
onUnload() {
},
async onShow() {




    this.setData({
            xingbieList: ["请选择性别", "男", "女"],
            xueliList: ["请选择学历", "小学", "初中", "高中", "中专", "大专", "本科", "研究生", "博士"],
            shifoubiyeList: ["请选择是否毕业", "是", "否"],
            xiangmufuzerenList: ["请选择项目负责人", "是", "否"]
    })






    this.setData({
            leixingList:  "在校生,毕业生".split(',')
    })



const chengshiRes = await sheng("option/chengshi/chengshi")
this.setData({
    chengshiList: chengshiRes.data
})

    const  yuanqu = await option('yuanqu/yuanqu')
    this.setData({
            yuanquList: yuanqu.data
    })

    const  jiedao = await option('jiedao/jiedao')
    this.setData({
            jiedaoList: jiedao.data
    })

    // 获取学校和学院列表（如有城市联动可补充）
    const xuexiaoRes = await option('xuexiao/xuexiao')
    let xuexiaoList = xuexiaoRes.data || [];
    if (!xuexiaoList[0] || xuexiaoList[0] !== '请选择学校') xuexiaoList = ['请选择学校', ...xuexiaoList];
    this.setData({
        xuexiaoList: xuexiaoList,
        xuexiaoIndex: 0
    })
    const xueyuanRes = await option('xueyuan/xueyuan')
    let xueyuanList = xueyuanRes.data || [];
    if (!xueyuanList[0] || xueyuanList[0] !== '请选择学院') xueyuanList = ['请选择学院', ...xueyuanList];
    this.setData({
        xueyuanList: xueyuanList,
        xueyuanIndex: 0
    })

},







xuehaoInput(e) {
this.setData({
    xuehao: e.detail.value
})
},

mimaInput(e) {
    const value = e.detail.value;
    let error = '';
    if (value && !/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,12}$/.test(value)) {
        error = '密码需为6-12位字母和数字组合';
    }
    this.setData({
        mima: value,
        mimaError: error
    });
},
mima2Input(e) {
    this.setData({
        mima2: e.detail.value
    });
},
mima2Blur(e) {
    const value = e.detail.value;
    let error = '';
    if (value !== this.data.mima) {
        error = '两次密码输入不一致';
    }
    this.setData({
        mima2Error: error
    });
},

xueshengxingmingInput(e) {
    const value = e.detail.value;
    let error = '';
    if (value && !/^[\u4e00-\u9fa5]{2,6}$/.test(value)) {
        error = '姓名需为2-6个汉字';
    }
    this.setData({
        xueshengxingming: value,
        xueshengxingmingError: error
    });
},

xingbieChange(e) {
const selectedIndex = e.detail.value;
    this.setData({
            xingbieIndex: selectedIndex,
    });
},

xueyuanInput(e) {
this.setData({
    xueyuan: e.detail.value
})
},

zhuanyeInput(e) {
this.setData({
    zhuanye: e.detail.value
})
},

nianjiInput(e) {
this.setData({
    nianji: e.detail.value
})
},

xueliChange(e) {
const selectedIndex = e.detail.value;
    this.setData({
            xueliIndex: selectedIndex,
    });
},

shifoubiyeChange(e) {
const selectedIndex = e.detail.value;
    this.setData({
            shifoubiyeIndex: selectedIndex,
    });
},

biyenianfenInput(e) {
this.setData({
    biyenianfen: e.detail.value
})
},

xiangmufuzerenChange(e) {
const selectedIndex = e.detail.value;
    this.setData({
            xiangmufuzerenIndex: selectedIndex,
    });
},

suozaixuexiaoInput(e) {
this.setData({
    suozaixuexiao: e.detail.value
})
},

youxiangInput(e) {
this.setData({
    youxiang: e.detail.value
})
},


touxiangTap() {
wx.chooseImage({
count: 1,
sizeType: ['compressed'],
sourceType: ['album', 'camera'],
success: async (res) => {
const tempFilePaths = res.tempFilePaths;
let tempPathtouxiang= tempFilePaths[0]
// 本地临时图片的路径
this.setData({
    tempPathtouxiang,
})
// 上传网络图片
const  baseURL= wx.getStorageSync('baseURL')
    if(baseURL){
        wx.uploadFile({
            url: `${baseURL}/file/upload`,
            filePath: res.tempFilePaths[0],
            name: 'file',
            header: {
                'Token': wx.getStorageSync('token')
            },
            success: (uploadFileRes) => {
                let result = JSON.parse(uploadFileRes.data);
                // result.file是上传成功为网络图片的名称
                if (result.code == 0) {
                    this.setData({
                            touxiang: 'file/' + result.file
                    })
                } else {
                    wx.showToast({
                        title: result.msg,
                        icon: 'none',
                        duration: 2000
                    });
                }
            }
        })
    }



}
})
},

chuangyelingyuInput(e) {
this.setData({
    chuangyelingyu: e.detail.value
})
},

canjiahuodongInput(e) {
this.setData({
    canjiahuodong: e.detail.value
})
},

canyuxiangmuInput(e) {
this.setData({
    canyuxiangmu: e.detail.value
})
},

leixingChange(e) {
const selectedIndex = e.detail.value;
    this.setData({
            leixingIndex: selectedIndex,
    });
},

async chengshiChange(e) {
const selectedIndex = e.detail.value;
const name=this.data.levelTow
const curName= name.replace('List','')
let shiData = await levelOption(`option/${curName}/${curName}`, "chengshi",this.data.chengshiList[selectedIndex])

    this.setData({
[name]:shiData.data,
chengshiIndex: selectedIndex,
});

},

async yuanquChange(e) {
const selectedIndex = e.detail.value;
const name=this.data.levelThree
const curName= name.replace('List','')
let res= await levelOption(`option/${curName}/${curName}`," yuanqu", this.data.yuanquList[selectedIndex])
this.setData({
[name]:res.data,
yuanquIndex: selectedIndex,
});

},

async jiedaoChange(e) {
const selectedIndex = e.detail.value;
this.setData({
jiedaoIndex:  selectedIndex,
});

},

async sendCodeHandler() {
if (!this.data.canSendCode) {
return;
}
if (this.data.email == "") {
wx.showToast({
    title: '请输入邮箱',
    icon: 'none'
})
return;
} else {
if (!utils.validata("email",this.data.email)) {
    wx.showToast({
        title: '请输入有效邮箱',
        icon: 'none'
    })
    return;
} else {
    const res = await SendverificationCode("chuangyezhe", 'sendemail','email',  this.data.email)

    this.setData({
        smscode: res.data
    })
}
}
this.setData({
canSendCode: false,
});
let time = this.data.countdown;
let timer = setInterval(() => {
time--;
this.setData({
    countdown: time, // 更新倒计时的时间
});
if (time <= 0) {
    clearInterval(timer); // 倒计时结束，清除定时器
    this.setData({
        buttonText: '发送验证码',
        canSendCode: true,
        countdown: 60
    });
}
}, 1000);

},

xuexiaoChange(e) {
    this.setData({
        xuexiaoIndex: e.detail.value
    })
    // 可选：根据学校联动学院
    // 若有联动，重新拉取学院并加提示项
},
xueyuanChange(e) {
    this.setData({
        xueyuanIndex: e.detail.value
    })
},
shoujihaomaInput(e) {
    this.setData({
        shoujihaoma: e.detail.value
    })
},
inputSmscode2Input(e) {
    this.setData({
        inputSmscode2: e.detail.value
    })
},
async sendSmsCodeHandler() {
    if (!this.data.canSendSmsCode) return;
    if (!this.data.shoujihaoma) {
        wx.showToast({ title: '请输入手机号', icon: 'none' });
        return;
    }
    // 手机号格式校验
    if (!/^1[3-9]\d{9}$/.test(this.data.shoujihaoma)) {
        wx.showToast({ title: '手机号格式不正确', icon: 'none' });
        return;
    }
    // 按网页端方式调用接口
    const res = await request({
        url: `/daoshi/sendsms?mobile=${this.data.shoujihaoma}`,
        method: 'get',
    });
    if (res.code === 0 || res.data?.code === 0) {
        wx.showToast({ title: '验证码发送成功', icon: 'success' });
        this.setData({ canSendSmsCode: false });
        let time = this.data.countdown2;
        let timer = setInterval(() => {
            time--;
            this.setData({ countdown2: time });
            if (time <= 0) {
                clearInterval(timer);
                this.setData({ buttonText2: '发送验证码', canSendSmsCode: true, countdown2: 60 });
            }
        }, 1000);
    } else {
        wx.showToast({ title: res.msg || (res.data && res.data.msg) || '发送失败', icon: 'none' });
    }
},
async register() {
    // ... existing code ...
    // 校验顺序和必填项严格按网页端
    if (!this.data.shifoubiyeList[this.data.shifoubiyeIndex]) {
        wx.showToast({ title: '请选择是否毕业', icon: 'none' }); return;
    }
    if (!this.data.xuehao) {
        wx.showToast({ title: this.data.shifoubiyeList[this.data.shifoubiyeIndex]==='是'?'请输入账号':'请输入学号', icon: 'none' }); return;
    }
    if (!this.data.xueshengxingming) {
        wx.showToast({ title: '请输入姓名', icon: 'none' }); return;
    }
    if (!/^[\u4e00-\u9fa5]{2,6}$/.test(this.data.xueshengxingming)) {
        wx.showToast({ title: '姓名需为2-6个汉字', icon: 'none' }); return;
    }
    if (!this.data.xingbieList[this.data.xingbieIndex]) {
        wx.showToast({ title: '请选择性别', icon: 'none' }); return;
    }
    if (!this.data.mima) {
        wx.showToast({ title: '请输入密码', icon: 'none' }); return;
    }
    if (!/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,12}$/.test(this.data.mima)) {
        wx.showToast({ title: '密码需为6-12位字母和数字组合', icon: 'none' }); return;
    }
    if (!this.data.mima2) {
        wx.showToast({ title: '请输入确认密码', icon: 'none' }); return;
    }
    if (this.data.mima !== this.data.mima2) {
        wx.showToast({ title: '密码与确认密码不一致', icon: 'none' }); return;
    }
    if (!this.data.chengshiList[this.data.chengshiIndex]) {
        wx.showToast({ title: '请选择城市', icon: 'none' }); return;
    }
    if (this.data.shifoubiyeList[this.data.shifoubiyeIndex]==='是') {
        if (!this.data.yuanquList[this.data.yuanquIndex]) { wx.showToast({ title: '请选择园区', icon: 'none' }); return; }
        if (!this.data.jiedaoList[this.data.jiedaoIndex]) { wx.showToast({ title: '请选择街道', icon: 'none' }); return; }
        if (!this.data.biyenianfen) { wx.showToast({ title: '请输入毕业年份', icon: 'none' }); return; }
        if (parseInt(this.data.biyenianfen)<1980) { wx.showToast({ title: '毕业年份不能小于1980', icon: 'none' }); return; }
    } else {
        if (!this.data.xuexiaoList[this.data.xuexiaoIndex]) { wx.showToast({ title: '请选择学校', icon: 'none' }); return; }
        if (!this.data.xueyuanList[this.data.xueyuanIndex]) { wx.showToast({ title: '请选择学院', icon: 'none' }); return; }
        if (!this.data.nianji) { wx.showToast({ title: '请输入年级', icon: 'none' }); return; }
    }
    if (!this.data.zhuanye) { wx.showToast({ title: '请输入专业', icon: 'none' }); return; }
    if (!this.data.xueliList[this.data.xueliIndex]) { wx.showToast({ title: '请选择学历', icon: 'none' }); return; }
    if (!this.data.xiangmufuzerenList[this.data.xiangmufuzerenIndex]) { wx.showToast({ title: '请选择项目负责人', icon: 'none' }); return; }
    if (!this.data.email) { wx.showToast({ title: '请输入邮箱', icon: 'none' }); return; }
    if (!utils.validata('email', this.data.email)) { wx.showToast({ title: '请输入有效邮箱', icon: 'none' }); return; }
    if (!this.data.inputSmscode) { wx.showToast({ title: '请输入邮箱验证码', icon: 'none' }); return; }
    if (!this.data.shoujihaoma) { wx.showToast({ title: '请输入手机号', icon: 'none' }); return; }
    if (!/^1[3-9]\d{9}$/.test(this.data.shoujihaoma)) { wx.showToast({ title: '手机号格式不正确', icon: 'none' }); return; }
    if (!this.data.inputSmscode2) { wx.showToast({ title: '请输入短信验证码', icon: 'none' }); return; }
    // ... existing code ...
    const regex = new RegExp(wx.getStorageSync('baseURL'), 'g');
    const resultObj = {
        xuehao: this.data.xuehao,
        mima: this.data.mima,
        mima2: this.data.mima2,
        xueshengxingming: this.data.xueshengxingming,
        xingbie: this.data.xingbieList[this.data.xingbieIndex],
        xueyuan: this.data.shifoubiyeList[this.data.shifoubiyeIndex]==='否'?this.data.xueyuanList[this.data.xueyuanIndex]:undefined,
        zhuanye: this.data.zhuanye,
        nianji: this.data.shifoubiyeList[this.data.shifoubiyeIndex]==='否'?this.data.nianji:undefined,
        xueli: this.data.xueliList[this.data.xueliIndex],
        shifoubiye: this.data.shifoubiyeList[this.data.shifoubiyeIndex],
        biyenianfen: this.data.shifoubiyeList[this.data.shifoubiyeIndex]==='是'?this.data.biyenianfen:undefined,
        xiangmufuzeren: this.data.xiangmufuzerenList[this.data.xiangmufuzerenIndex],
        suozaixuexiao: this.data.shifoubiyeList[this.data.shifoubiyeIndex]==='否'?this.data.xuexiaoList[this.data.xuexiaoIndex]:undefined,
        touxiang: this.data.touxiang?this.data.touxiang.replace(regex, ''):'',
        chuangyelingyu: this.data.chuangyelingyu,
        canjiahuodong: this.data.canjiahuodong,
        canyuxiangmu: this.data.canyuxiangmu,
        chengshi: this.data.chengshiList[this.data.chengshiIndex],
        yuanqu: this.data.shifoubiyeList[this.data.shifoubiyeIndex]==='是'?this.data.yuanquList[this.data.yuanquIndex]:undefined,
        jiedao: this.data.shifoubiyeList[this.data.shifoubiyeIndex]==='是'?this.data.jiedaoList[this.data.jiedaoIndex]:undefined,
        email: this.data.email,
        shoujihaoma: this.data.shoujihaoma,
        inputSmscode: this.data.inputSmscode,
        inputSmscode2: this.data.inputSmscode2,
    }
    // 删除自动填充空字段为“无”的逻辑
    // Object.keys(resultObj).forEach(key => {
    //     if (![ 'email', 'shoujihaoma', 'inputSmscode', 'inputSmscode2' ].includes(key) && (resultObj[key] === undefined || resultObj[key] === null || resultObj[key] === '')) {
    //         resultObj[key] = '无';
    //     }
    // });
    // 邮箱验证码校验
    const res = await smscode('chuangyezhe', 'emailcode', this.data.inputSmscode, resultObj)
    if (res.code == 0) {
        // 短信验证码校验（如有后端接口可补充）
        wx.navigateTo({ url: '../login/login' })
    } else {
        wx.showToast({ title: res.msg, icon: 'none' })
    }
}
})